﻿using DesktopShortcutMonitor.Model;
using DesktopShortcutMonitor.Monitor;
using IWshRuntimeLibrary;
using Microsoft.Win32;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace DesktopShortcutMonitor
{
    public partial class MainForm : UIForm
    {
        Config _config;
        public MainForm()
        {
            InitializeComponent();
        }

        private void settingToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SettingsForm frm = new SettingsForm();
            frm.ShowDialog();
            this.nudScanIntervalSec.Value = _config.ScanIntervalSec;
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            _config = App.Ins.Config;

            nudScanIntervalSec.Value = _config.ScanIntervalSec;
            grid.DataSource = _config.Datas;

            // 启用编辑功能
            grid.Enabled = false;
            //grid.ReadOnly = false;
            //grid.AllowUserToAddRows = false;
            //grid.AllowUserToDeleteRows = false;

            //控件最小尺寸
            grid.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
            grid.AllowUserToResizeColumns = true;

            for (int rowIndex = 0; rowIndex < _config.Datas.Count(); rowIndex++)
            {
                grid.Rows[rowIndex].Cells[0].Value = 1;
                grid.Rows[rowIndex].Cells[1].Value = "OK";
                grid.Rows[rowIndex].Cells[1].Style.BackColor = Color.Green;
                grid.Rows[rowIndex].Cells[2].Value = DateTime.Now.ToString("yyyyMMdd HHmmss");
            }

            this.WindowState = FormWindowState.Minimized;
            this.ShowInTaskbar = false;


            Thread thread = new Thread(ThreadMain);
            thread.IsBackground = true;
            thread.Start();

            this.notifyIcon1.Text = Application.ProductName;
            this.Resize += MainForm_Resize;

            SetAutoStart();
        }

        private void MainForm_Resize(object sender, EventArgs e)
        {
            if (WindowState == FormWindowState.Minimized)
            {
                Hide();
                notifyIcon1.Visible = true;
            }
        }
        private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            Show();
            WindowState = FormWindowState.Normal;
            notifyIcon1.Visible = false;
            this.ShowInTaskbar = true;
            BringToFront();
        }

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (e.CloseReason == CloseReason.UserClosing)
            {
                e.Cancel = true;
                WindowState = FormWindowState.Minimized;
                UIMessageBox.ShowInfo("不能关闭,已经最小化到托盘!", false, 3);
            }
        }

        private void ThreadMain()
        {
            MonitorFile monitorFile = new MonitorFile();
            int count = 0;
            while (true)
            {
                try
                {

                    ShowLog($"WaitNext");
                    Thread.Sleep(TimeSpan.FromSeconds(_config.ScanIntervalSec));
                    // 获取桌面路径
                    string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);

                    // 扫描可执行文件（排除快捷方式）
                    var exeFiles = monitorFile.ScanDesktopExecutables(desktopPath);
                    ShowLog($"ScanDesktopExecutables");

                    #region DisplayScanResults
                    for (int rowIndex = 0; rowIndex < _config.Datas.Count(); rowIndex++)
                    {
                        SingleConfig singleConfig = _config.Datas[rowIndex];

                        if (singleConfig.CheckContainFile)
                        {///检测被监控程序的所在目录要包含某文件
                            var machingFiles = exeFiles.Where(s =>
                            {
                                if (System.IO.File.Exists(Path.Combine(Path.GetDirectoryName(s.FullPath), singleConfig.CheckContainFileName)))
                                {
                                    return true;
                                }
                                else
                                {
                                    return false;
                                }
                            });
                            ShowAlert(singleConfig.CheckLinkNamePattern, rowIndex, machingFiles);
                        }
                        else
                        {
                            var machingFiles = exeFiles.Where(s => s.FileName.Contains(singleConfig.CheckLinkNamePattern));
                            ShowAlert(singleConfig.CheckLinkNamePattern, rowIndex, machingFiles);
                        }
                        ShowLog($"{rowIndex}: {singleConfig.CheckLinkNamePattern}");
                    }
                    #endregion

                    ShowLog("end********************************");
                    count++;
                    if (count > 3)
                    {
                        count = 0;
                        ShowLog();
                    }
                }
                catch (Exception ex)
                {

                }
            }
        }

        private void ShowLog(string strLog = "清空")
        {
            if (this.InvokeRequired)
            {
                this.BeginInvoke(new Action(() => ShowLog(strLog)));
                return;
            }
            else
            {
                if (strLog == "清空")
                {
                    rtbLog.Clear();
                    return;
                }

                rtbLog.AppendText($"{DateTime.Now} {strLog}\r");
            }
        }



        #region 程序比对

        private void ShowAlert(string nameDesc, int rowIndex, IEnumerable<ExeFileInfo> machingFiles)
        {
            int count = null == machingFiles ? 0 : machingFiles.Count();
            string message;
            switch (count)
            {
                case 0:
                    message = "未找到有效快捷方式！";
                    break;
                case 1:
                    message = $"发现{count}个快捷方式,数量OK！";
                    break;
                default:
                    message = $"发现{count}个快捷方式,数量异常！";
                    break;
            }
            bool isOK = 1 == count;
            this.BeginInvoke(new Action(() =>
                {
                    grid.Rows[rowIndex].Cells[0].Value = count;
                    grid.Rows[rowIndex].Cells[1].Value = isOK ? "OK" : "NG";
                    grid.Rows[rowIndex].Cells[1].Style.BackColor = isOK ? Color.Green : Color.Red;
                    grid.Rows[rowIndex].Cells[2].Value = DateTime.Now.ToString("yyyyMMdd HHmmss");
                }));

            if (!isOK)
            {
                UIMessageBox.ShowMessageDialog($"程序{nameDesc} {message}", "异常", true, UIStyle.Red, true, UIMessageDialogButtons.Ok);
            }
        }

        /// <summary>
        /// 软件开机自启动
        /// </summary>
        private void SetAutoStart()
        {
            try
            {
                using (var key = Registry.CurrentUser.OpenSubKey(
                    @"Software\Microsoft\Windows\CurrentVersion\Run", true))
                {
                    string productName = Application.ProductName;

                    var exePath = $"\"{Application.ExecutablePath}\"";
                    if (key.GetValue(productName)?.ToString() != exePath)
                    {
                        key.SetValue(productName, exePath);
                    }
                }
            }
            catch { /* 处理权限异常 */ }
        }


        #endregion

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string varName = string.Empty;
            if (UIInputDialog.ShowInputStringDialog(ref varName, UIStyle.Blue, true, "请输入口令"))
            {
                if (!varName.ToLower().Contains("secote789"))
                {
                    UIMessageBox.ShowError($"对不起，口令错误");
                    return;
                }
            }

            notifyIcon1.Dispose();
            Application.Exit();
        }
    }//end class
}
